/* eslint-disable default-case */
import { message } from 'antd';
import {
  checkCreateBillTask,
  getProgress,
  getNoBillEntered,
  getOnceData,
  getWageGeneration,
  getGenerateBills,
  getAllGenerateBills,
  downloadTemplate,
  singleExportFile,
  mergeExportFile,
  getUploadFile,
} from '@/services/chargemanage';
import * as service from '@/services/socket';

export default {
  state: {
    isHasTask: false,
    billTaskId: null,
    taskCode: null,
    selectMessage: [],
    allDataList: [],
    formFieldsValue: { defaultFlag: '1' },
    isdefaultFlag: '1',
    noBillData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    onceBillData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    wageGenerationData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    resultInfo: {
      // 结果数据必传
      batchName: '生成账单', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/csBill/downBillException', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    progressPercent: 0,
  },
  effects: {
    // 判断有无账单任务
    *checkCreateBillTask(_, { call, put }) {
      const response = yield call(checkCreateBillTask);
      if (response.success && response.data) {
        if (response.data.taskCode === 3) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              billTaskId: response.data.billTaskId,
              taskCode: response.data.taskCode,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      }
    },
    // 获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.rate },
        });
      }
      return response;
    },

    // 获取未进账单其它数据
    *getNoBillEnteredData({ payload }, { call, put }) {
      const response = yield call(getNoBillEntered, payload);
      yield put({
        type: 'getNoBillEnteredDataList',
        payload: {
          data: [],
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (response.success) {
        if (response.data && response.data.pageRecords) {
          response.data.pageRecords.map(item => {
            const temp = item;
            temp.key = `${item.custId}^${item.defaultFlag}^${item.empId}^${item.feeYm}^${
              item.unnaturalCause
            }^${item.cardNo}`;
            return true;
          });
        }

        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'getNoBillEnteredDataList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        yield put({
          type: 'getNoBillEnteredDataList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
        message.warning(response.message || '获取列表失败');
      }
    },

    // 获取未进账单一次性数据
    *getOnceDetailData({ payload }, { call, put }) {
      const response = yield call(getOnceData, payload);
      yield put({
        type: 'getOnceDataList',
        payload: {
          data: [],
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (response.success) {
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'getOnceDataList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        yield put({
          type: 'getOnceDataList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
        message.warning(response.message || '获取列表失败');
      }
    },

    // 代发工资代报税
    *getWageGenerationData({ payload }, { call, put }) {
      const response = yield call(getWageGeneration, payload);
      yield put({
        type: 'getWageGenerationDataList',
        payload: {
          data: [],
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (response.success) {
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        yield put({
          type: 'getWageGenerationDataList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        yield put({
          type: 'getWageGenerationDataList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
        message.warning(response.message || '获取列表失败');
      }
    },

    // 未进账单 - 生产账单
    *generateBills({ payload }, { call }) {
      const response = yield call(getGenerateBills, payload);
      return response;
    },

    // 未进账单 - 生产账单
    *allGenerateBills({ payload }, { call }) {
      const response = yield call(getAllGenerateBills, payload);
      return response;
    },

    // 下载模板
    *updownfiles({ payload }, { call }) {
      const response = yield call(downloadTemplate, payload);
      return response;
    },

    // 账单单个下载
    *singleExport({ payload }, { call }) {
      const response = yield call(singleExportFile, payload);
      return response;
    },

    // 账单合并下载
    *mergeExport({ payload }, { call }) {
      const response = yield call(mergeExportFile, payload);
      return response;
    },

    // 客户账单 - 账单下载
    *uploadFile({ payload }, { call }) {
      const response = yield call(getUploadFile, payload);
      return response;
    },

    // 上传文件:批量进度:获取batchId后获取进度 :batchType：1/2:未进账单生成(tabpaneid)
    *uploadFileWithProgress(
      {
        payload: { batchType, params },
      },
      { call, put }
    ) {
      const response = yield call(batchType === 1 ? getGenerateBills : getAllGenerateBills, params);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data.batchId,
            progressPercent: 0,
          },
        });
        if (batchType === 1) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: response.data && response.data.taskCode === 3,
            },
          });
          if (response.data.taskCode === 1) {
            if (response.data && response.data.successProp !== 100) {
              yield put({
                type: 'updateModelData',
                payload: {
                  showProgress: true,
                },
              });
              yield call(service.socketChannel, {
                type: 'sub',
                data: {
                  to: response.data && (response.data.batchId || response.data),
                  type: 'csBill',
                },
              });
            } else {
              yield put({
                type: 'updateBatchTask',
                payload: response.data,
              });
            }
          } else if (response.data.taskCode === 3) {
            message.warning('当前有账单任务正在生成，请稍后操作！');
          }
        } else if (batchType === 2) {
          if (response.data && response.data.successProp !== 100) {
            yield put({
              type: 'updateModelData',
              payload: {
                showProgress: true,
              },
            });
            yield call(service.socketChannel, {
              type: 'sub',
              data: {
                to: response.data && (response.data.batchId || response.data),
                type: 'csBill',
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        }
      } else {
        // 操作失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.customerbillcs);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 选中的数据
    getSelectedData(state, { payload }) {
      // eslint-disable-next-line array-callback-return
      payload.map(item => {
        state.selectMessage.push(item);
      });
      return {
        ...state,
        selectMessage: state.selectMessage,
      };
    },

    // 清空一下数据
    // eslint-disable-next-line no-empty-pattern
    clearData(state, {}) {
      return {
        ...state,
        selectMessage: [],
      };
    },

    defaultFlagModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 未进账单其它数据
    getNoBillEnteredDataList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list =
        data && data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        noBillData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },

    // 未进账单一次性数据
    getOnceDataList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list =
        data && data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        onceBillData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },

    // 代发工资代报税
    getWageGenerationDataList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list =
        data && data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        wageGenerationData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },

    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { resultInfo, showProgress } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        if (payload.errorCount) {
          resultInfo.errorParams = {
            batchId: payload.batchId,
          };
          resultInfo.errorCount = payload.errorCount || 0;
        }
        resultInfo.taskCount = payload.taskNumber;
        resultInfo.billCount = payload.successCount;
        resultInfo.feeYm =
          payload.feeYm &&
          `${payload.feeYm.toString().substr(0, 4)}-${payload.feeYm.toString().substr(4, 5)}`;
        resultInfo.successCount = payload.successCount;
        resultInfo.taskFlag = payload.taskFlag || 1;
        resultInfo = { ...resultInfo, ...payload };
      }
      return {
        ...state,
        showProgress,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'csBill':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
